package com.jy.appmarket.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.jy.appmarket.R;
import com.jy.appmarket.fragment.FragmentScreenshot;
import com.jy.appmarket.utils.UITools;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.List;

/**
 * 类说明：
 *
 * @author Toby.chen
 * @version 1.0
 * @date 2013-6-5
 */

public class ScreenShotsActivity extends FragmentActivity implements OnPageChangeListener {
    public static class DrawableHolder {
        public static int index;
        public static Drawable drawable;
    }

    //private static final String TAG = "ScreenShotsActivity";

    public static String EXTRA_INDEX = "screenshots_index";
    public static String EXTRA_NORMAL_LIST = "screenshots_normal_list";
    public static String EXTRA_SMALL_LIST = "screenshots_small_list";
    public static String EXTRA_SMALL_IMAGE_SIZE_LIST = "screenshots_small_size_list";

    private ViewPager mViewPager;
    private ScreenShotsAdapter mAdapter;
    private int mIndex;
    private List<String> mSmall;
    private List<String> mNormal;
    private int[] mSmallSizeArray = null;

    private ImageView mAniImageView = null;
    private Rect mImageOrgRect = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_screenshots);

        getExtras();
        mAniImageView = findViewById(R.id.animation_view);
        setAnimViewStartPosition();

        mViewPager = findViewById(R.id.screenshots_viewpager);
        mViewPager.addOnPageChangeListener(this);

        mAdapter = new ScreenShotsAdapter(getSupportFragmentManager(), mSmall,
                mNormal, mSmallSizeArray);
        mViewPager.setAdapter(mAdapter);
        if (mSmall != null && mIndex > 0 && mIndex < mSmall.size()) {
            mViewPager.setCurrentItem(mIndex);
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startAinmation();
            }
        }, 50);
    }

    private void startEndAnimation() {
        mViewPager.setVisibility(View.GONE);
        mAniImageView.setVisibility(View.VISIBLE);

        final Rect r = calcAnimViewEndPos();
        AnimationSet as = new AnimationSet(true);
        as.setDuration(300);
        as.setFillAfter(true);
        as.setInterpolator(new AccelerateInterpolator());

        float ws = (float) mImageOrgRect.width() / (float) r.width();
        float hs = (float) mImageOrgRect.height() / (float) r.height();
        final ScaleAnimation sa = new ScaleAnimation(1.0f, ws, 1.0f, hs,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f);

        TranslateAnimation ta = new TranslateAnimation(0,
                (mImageOrgRect.left - r.left) / ws, 0,
                (mImageOrgRect.top - r.top) / hs);


        AlphaAnimation aa = new AlphaAnimation(1.0f, 0.3f);

        as.addAnimation(ta);
        as.addAnimation(sa);
        as.addAnimation(aa);
        as.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                new Handler().postDelayed(new Runnable() { //解决部分手机卡顿
                    @Override
                    public void run() {
                        finish();
                        overridePendingTransition(0, 0);
                    }
                }, 20);


            }
        });

        mAniImageView.startAnimation(as);

    }

    private void startAinmation() {
        final Rect r = calcAnimViewEndPos();
        AnimationSet as = new AnimationSet(true);
        as.setDuration(300);
        as.setInterpolator(new AccelerateInterpolator());

        float ws = (float) r.width() / (float) mImageOrgRect.width();
        float hs = (float) r.height() / (float) mImageOrgRect.height();
        final ScaleAnimation sa = new ScaleAnimation(1.0f, ws, 1.0f, hs,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                0.0f);

        TranslateAnimation ta = new TranslateAnimation(0,
                (r.left - mImageOrgRect.left) / ws, 0,
                (r.top - mImageOrgRect.top) / hs);

        as.addAnimation(ta);
        as.addAnimation(sa);
        as.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mViewPager.setVisibility(View.VISIBLE);
                mAniImageView.setVisibility(View.GONE);
                setViewPostion(mAniImageView, r.left, r.top, r.width());
                setViewSize(mAniImageView, r.width(), r.height());

            }
        });

        mAniImageView.startAnimation(as);
    }

    private void setViewPostion(View view, int left, int top, int w) {
        MarginLayoutParams margin = new MarginLayoutParams(
                view.getLayoutParams());
        int sw = (UITools.getDeviceScreenWidthHeight(this))[0];
        margin.setMargins(left, top, sw - left - w, 0);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                margin);
        view.setLayoutParams(layoutParams);
    }

    private void setViewSize(View view, int w, int h) {
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        lp.width = w;
        lp.height = h;
        view.setLayoutParams(lp);
    }

    private void setAnimViewStartPosition() {
        if (ScreenShotsActivity.DrawableHolder.drawable != null) {
            mAniImageView
                    .setImageDrawable(ScreenShotsActivity.DrawableHolder.drawable);

            setViewPostion(mAniImageView, mImageOrgRect.left,
                    mImageOrgRect.top, mImageOrgRect.width());
            setViewSize(mAniImageView, mImageOrgRect.width(),
                    mImageOrgRect.height());
        }
    }

    private int[] calcAdaptionImageSize(int w, int h) {
        int[] size = new int[2];
        int[] screenSize = UITools.getDeviceScreenWidthHeight(this);
        int screenW = screenSize[0];

        size[0] = screenW;
        size[1] = (int) ((float) h * ((float) screenW / (float) w));

        return size;
    }

    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private Rect calcAnimViewEndPos() {
        Rect r = new Rect();

        int iw = 0, ih = 0;
        if (mSmallSizeArray != null && mIndex * 2 + 1 < mSmallSizeArray.length) {
            iw = mSmallSizeArray[mIndex * 2];
            ih = mSmallSizeArray[mIndex * 2 + 1];
        }

        int[] wh = calcAdaptionImageSize(iw, ih);
        r.left = 0;
        r.right = r.left + wh[0];

        int heightTotal = (UITools.getDeviceScreenWidthHeight(this))[1]
                - getStatusBarHeight();
        int top = (heightTotal - wh[1]) / 2;

        r.top = top;
        r.bottom = top + wh[1];

        return r;
    }

    private void getExtras() {
        Intent it = getIntent();
        if (it != null) {
            mImageOrgRect = it.getSourceBounds();

            mIndex = it.getIntExtra(EXTRA_INDEX, 0);
            mSmall = it.getStringArrayListExtra(EXTRA_SMALL_LIST);
            mNormal = it.getStringArrayListExtra(EXTRA_NORMAL_LIST);
            mSmallSizeArray = it.getIntArrayExtra(EXTRA_SMALL_IMAGE_SIZE_LIST);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onBackPressed() {
        startEndAnimation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mViewPager.removeOnPageChangeListener(this);
    }

    public void activityFinish() {
        startEndAnimation();
    }

    @Override
    public void onPageSelected(int arg0) {
        FragmentScreenshot frg = (FragmentScreenshot) mAdapter.getFragment(arg0);
        if (frg == null) {
            return;
        }

        Drawable d = frg.getImageDrawable();
        if (d != null) {
            mAniImageView.setImageDrawable(d);
        }

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        //do nothing
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        //do nothing
    }

    public static class ScreenShotsAdapter extends FragmentPagerAdapter {
        private List<String> mSmall;
        private List<String> mNormal;
        private int[] mSmallSize;


        private HashMap<Integer, Fragment> mDataMap = new HashMap<Integer, Fragment>();

        public ScreenShotsAdapter(FragmentManager fm, List<String> small,
                                  List<String> normal, int[] smallSize) {
            super(fm);
            mSmall = small;
            mNormal = normal;
            mSmallSize = smallSize;
        }

        public Fragment getFragment(int pos) {
            return mDataMap.get(Integer.valueOf(pos));
        }

        @Override
        public int getCount() {
            if (mSmall == null) {
                return 0;
            }
            // 以small为准
            return mSmall.size();
        }

        @Override
        public Fragment getItem(int position) {
            Fragment frag = mDataMap.get(Integer.valueOf(position));
            if (frag == null) {
                String small = mSmall.get(position);
                String normal = null;
                if (mNormal != null && mNormal.size() > position) {
                    normal = mNormal.get(position);
                }

                int w = 0, h = 0;
                if (mSmallSize != null && position * 2 + 1 < mSmallSize.length) {
                    w = mSmallSize[position * 2];
                    h = mSmallSize[position * 2 + 1];
                }
                frag = FragmentScreenshot
                        .newInstance(position, small, normal, w, h);
                mDataMap.put(Integer.valueOf(position), frag);
            }

            return frag;
        }
    }

}
